"""
健康检查API路由
"""
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy import text
import psutil
import os

from core.database import get_db
from models.schemas import HealthResponse
from core.config import get_settings
from core.logger import api_logger

router = APIRouter()
settings = get_settings()


@router.get("/health", response_model=HealthResponse)
async def health_check(db: Session = Depends(get_db)):
    """健康检查"""
    try:
        # 检查数据库连接
        db.execute(text("SELECT 1"))
        db_status = "healthy"
    except Exception as e:
        db_status = f"unhealthy: {str(e)}"
    
    # 检查系统资源
    try:
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        services_status = {
            "database": db_status,
            "cpu": f"{cpu_percent}%",
            "memory": f"{memory.percent}%",
            "disk": f"{disk.percent}%"
        }
        
        # 判断整体状态
        overall_status = "healthy"
        if db_status != "healthy" or cpu_percent > 90 or memory.percent > 90 or disk.percent > 90:
            overall_status = "degraded"
        
        return HealthResponse(
            status=overall_status,
            timestamp=datetime.now(),
            version=settings.app_version,
            database=db_status,
            services=services_status
        )
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/health"})
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Health check failed"
        )


@router.get("/ready")
async def readiness_check():
    """就绪检查"""
    # 检查必要的服务是否准备就绪
    try:
        # 检查上传目录
        if not os.path.exists(settings.upload_dir):
            raise HTTPException(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                detail="Upload directory not ready"
            )
        
        # 检查解析结果目录
        if not os.path.exists(settings.parsed_results_dir):
            raise HTTPException(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                detail="Results directory not ready"
            )
        
        return {"status": "ready", "timestamp": datetime.now()}
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/ready"})
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Service not ready"
        )


@router.get("/live")
async def liveness_check():
    """存活检查"""
    return {"status": "alive", "timestamp": datetime.now()}


@router.get("/metrics")
async def get_metrics():
    """获取系统指标"""
    try:
        # 获取系统指标
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        # 获取网络信息
        network = psutil.net_io_counters()
        
        # 获取进程信息
        process = psutil.Process()
        process_info = {
            "cpu_percent": process.cpu_percent(),
            "memory_percent": process.memory_percent(),
            "memory_info": process.memory_info()._asdict(),
            "create_time": process.create_time(),
            "num_threads": process.num_threads()
        }
        
        return {
            "timestamp": datetime.now(),
            "system": {
                "cpu_percent": cpu_percent,
                "memory": {
                    "total": memory.total,
                    "available": memory.available,
                    "percent": memory.percent,
                    "used": memory.used,
                    "free": memory.free
                },
                "disk": {
                    "total": disk.total,
                    "used": disk.used,
                    "free": disk.free,
                    "percent": disk.percent
                },
                "network": {
                    "bytes_sent": network.bytes_sent,
                    "bytes_recv": network.bytes_recv,
                    "packets_sent": network.packets_sent,
                    "packets_recv": network.packets_recv
                }
            },
            "process": process_info
        }
        
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/metrics"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get metrics"
        )


# 导出路由器
health_router = router